package com.rentapark.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import services.SearchService;

import com.google.android.maps.GeoPoint;

import data.DB;
import data.OwnerListAdapter;
import data.Request;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import services.*;

//this activity is for displaying the user's settings
public class Profile extends Activity{
	String name;
	String idString;
	String phone;
	String car_no;
	int grade;
	int credit;
	DB parking_db;
	ProgressDialog progressDialog;
	//handles server's response
	private final Handler handler = new Handler() {  

		public void handleMessage(Message msg) {
			String result = msg.getData().getString("RESPONSE"); 
			Log.d("serverResponse",result);
			progressDialog.dismiss(); 
			SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);

			 //parsing the xml in order to get the user's information       
			try {

				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document doc = db.parse(new InputSource(new StringReader(result)));
				NodeList nodeList = doc.getElementsByTagName("Grade");
			
				
				if(nodeList != null && nodeList.getLength() > 0) {
					Element el = (Element)nodeList.item(0);
					grade = Integer.parseInt(el.getFirstChild().getNodeValue());
				}
				NodeList nodeSec = doc.getElementsByTagName("Credit");
				if(nodeSec != null && nodeSec.getLength() > 0) {
					Element el = (Element)nodeSec.item(0);
					credit = Integer.parseInt(el.getFirstChild().getNodeValue());
				}
				  TextView name = (TextView)findViewById(R.id.name);
				  name.setText(ref.getString("userName", "name"));
				  TextView iid = (TextView)findViewById(R.id.id);
				  iid.setText(ref.getString("my_id", "id"));
				  TextView txphone = (TextView)findViewById(R.id.phone);
				  txphone.setText(ref.getString("userPhone", phone));
				  TextView car = (TextView)findViewById(R.id.car);
				  car.setText(ref.getString("UserCarNo", car_no));
				  TextView tGrade = (TextView)findViewById(R.id.grade);
				  tGrade.setText(Integer.toString(grade));
				  TextView tCred = (TextView)findViewById(R.id.credit);
				  tCred.setText(Integer.toString(credit));
			}
			catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		} 
	};
	//onCreate
	public void onCreate(Bundle savedInstanceState){   
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);
		//get DB insttance
		  parking_db=DB.getInstance();
		  //perform request to server: http post asking for user's info
		  performRequest("http://"+parking_db.instanceDNS+":8080/ParkAndLetPark/UserInfo");
		  //this button is for the user to buy more credit
			Button buyButton = (Button)this.findViewById(R.id.buyCredit);
			buyButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					//buyCredit(final String uri,int credit);
					Log.d("app","buyCredit");
					final AlertDialog.Builder alert = new AlertDialog.Builder(Profile.this);
					alert.setTitle("Insert the number of credits you want to buy: ");
					final EditText input = new EditText(Profile.this);
                    alert.setView(input);
                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                        String value = input.getText().toString().trim();

                            Intent intent = new Intent(Profile.this, BuyCredit.class);
                            intent.putExtra("toBuy", Integer.parseInt(value));
                            Log.d("profile","want to buy"+value);
                            startService(intent);
                            finish();
                            
               }
                });

           alert.setNegativeButton("Cancel",
               new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.cancel();
                        }
                        });
                alert.show();

					}


			});
	}
	//this method sends an http post to the server with the user id and then the server returns all the user's data
	private void performRequest(final String uri) { 
		// create HTTP response handler to handle the HTTP response
		// the response data is extracted from the HTTP message and then it is wrapped in a message
		// which  is passed to the android handler for handling
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());   
					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);         
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 


		this.progressDialog = ProgressDialog.show(this, "", "executing");
		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(uri);
				parking_db=DB.getInstance();
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();

						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Request = doc.createElement("MSG_TYPE");
						Request.appendChild(doc.createTextNode("USER_INFO"));
						doc.appendChild(Request);

						Element Userid=doc.createElement("USER_ID");
						Userid.appendChild(doc.createTextNode(Double.toString(parking_db.userID)));//can be 0 on newUser!!
						Request.appendChild(Userid);


						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString",xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);

						String response = httpclient.execute(httppost,responseHandler);
						Log.d("","*server response* "+response);
					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					}

				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 
	}

}
